﻿using Dt261.ble;
using Dt261.help;
using Dt261.Model;
using Panuon.UI.Silver;
using Panuon.UI.Silver.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;

namespace Dt261.Views
{
    /// <summary>
    /// DeviceWindow.xaml 的交互逻辑
    /// </summary>
    public partial class DeviceWindow : Page
    {
      
        IPendingHandler handler;
         BleCore bluetooth;
        private string bindMac;
        private ObservableCollection<Device> knownDevices;

        private List<DeviceInformation> UnknownDevices = new List<DeviceInformation>();

        public string BindMac { get => bindMac; set => bindMac = value; }
        public ObservableCollection<Device> KnownDevices { get => knownDevices; set => knownDevices = value; }
        IniFile ini;
        public DeviceWindow()
        {
            InitializeComponent();

            bluetooth = BleCore.shareInstance();
            bluetooth.ValueChanged += eventRun;
            bluetooth.DeviceChanged += deviceRun;
            //KnownDevices.Add(new Device() { ID = "123", Name = "333" });
            KnownDevices = new ObservableCollection<Device>();
            ResultsListView.ItemsSource = KnownDevices;
            ReadConfigInfo();
        }

        public void eventRun(MsgType type, string str, byte[] data = null)
        {
            Console.WriteLine(data);
            Console.WriteLine(str);

            if(type == MsgType.BLEData)
            {
                Console.WriteLine(data);
                TLJCommand c = new TLJCommand();
                c.parseWithHexData(data);
            }



        }

        public void deviceRun(MsgType type, string str,string Id)
        {

            ThreadPool.QueueUserWorkItem(delegate
            {
                SynchronizationContext.SetSynchronizationContext(new
                    DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
                SynchronizationContext.Current.Post(pl =>
                {                    //里面写真正的业务内容  "蓝牙地址：" +
                   // logIni().IniWriteValue("Msg", DateTime.Now.ToString(), string.IsNullOrEmpty(str) ? "未知名称" : str + Id);
                     if(!string.IsNullOrEmpty(str) &&  str.Contains("261"))
                    {
                        var item = new Device() { ID = Id.Substring(Id.LastIndexOf("-") + 1), Name = string.IsNullOrEmpty(str) ? "未知" : str };
                        DataContext = item;

                        KnownDevices.Add(item);
                    }

                 

                    if (handler != null)
                    {
                        handler.Close();
                        handler = null;

                        if(KnownDevices.Count <= 0)
                        {
                            Notice.Show("未查找到可用测试设备", "提示", 3, MessageBoxIcon.Warning);
                        }
                    }
                    
                }, null);
            });
           
       
            Console.WriteLine(str + ":" + Id);
        }

        public async void EnumerateButton_Click_1(object sender, RoutedEventArgs e)
        {
            bluetooth.StopBleDeviceWatcher();
        
            handler = PendingBox.Show("正在查找蓝牙设备...", "请稍后", true, Application.Current.MainWindow, new PendingBoxConfigurations()
            {
                LoadingForeground = "#5DBBEC".ToColor().ToBrush(),
                ButtonBrush = "#5DBBEC".ToColor().ToBrush(),
            });
            handler.Cancel += delegate
            {
                handler.Close();
                bluetooth.StopBleDeviceWatcher();
            };
 
            this.KnownDevices.Clear();
         
            bluetooth.StartBleDeviceWatcher();


            //await Task.Delay(2000);
            //handler.UpdateMessage("Almost complete (2/2)...");
            // await Task.Delay(2000);



        }

        private void PairButton_Click_1(object sender, RoutedEventArgs e)
        {
            bluetooth.SelectDeviceFromIdAsync("f4:84:4c:46:23:db");
            //bluetooth.SelectDeviceFromIdAsync("66:4d:87:c7:a6:61");
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (1==1)//bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
                ArrayList list = new ArrayList();
                list.Add("0000 0000 00000000");
                TLJCommand com = new TLJCommand(CommandType.CommandType_DeviceFactory, CommandAction.CommandAction_Query, list);
                byte[] dd = com.getProtocolHex();
                bluetooth.Write(dd);
            }
        }


        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;

            var c = button.DataContext as Device;

            Notice.Show("已绑定听力测试设备："  + c.ID+"", "提示", 3, MessageBoxIcon.Success);
           //MessageBox.Show(c.Name + c.ID);
           // bluetooth.SelectDeviceFromIdAsync(c.ID);
            //// bluetooth.SelectDeviceFromIdAsync("f4:84:4c:46:23:db");
            //bluetooth.SelectDeviceFromIdAsync("66:4d:87:c7:a6:61");
            BindMac = c.ID;
            Bindmac.Text = BindMac;
            this.SaveDeviceInfo();

           bluetooth.Dispose();
        }

        private void ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        public void ReadConfigInfo()
        {
            var basePath = Environment.CurrentDirectory;

            string cfgINI = System.IO.Path.Combine(basePath, "device.ini");

            if (File.Exists(cfgINI))
            {
                IniFile ini = new IniFile(cfgINI);
                BindMac = ini.IniReadValue("Bind", "Device");
                Bindmac.Text = BindMac;
                //  SkinName = ini.IniReadValue("Skin", "Skin");
                // ServerType = ini.IniReadValue("Server", "Bridge");
            }
            else
            {
                Bindmac.Text = "未绑定设备";
            }
        }

        /// <summary>
        /// 保存信息
        /// </summary>
        private void SaveDeviceInfo()
        {
            var basePath = Environment.CurrentDirectory;

            string cfgINI = System.IO.Path.Combine(basePath, "device.ini");
            IniFile ini = new IniFile(cfgINI);
            ini.IniWriteValue("Bind", "Device", BindMac);
 
        }

#if DEBUG
        private IniFile logIni()
        {

            if (ini == null)
            {
                var basePath = Environment.CurrentDirectory;

                string cfgINI = System.IO.Path.Combine(basePath, "devicesearchlog.ini");
                ini = new IniFile(cfgINI);
                ini.IniWriteValue("开始搜索蓝牙", "Log", DateTime.Now.ToString());
            }

            return ini;
        }
#endif
    }
}
